package com.happy016.hystrix;

import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;


/**
 * 为consumer微服务添加hystrix容错回退
 * @author Linyb
 * @since 2017/10/12 15:57
 */
@Component
public class ConsumerFallbackProvider implements ZuulFallbackProvider {

    //指定为consumer微服务提供回退
    @Override
    public String getRoute() {
        return "consumer";
    }

    @Override
    public ClientHttpResponse fallbackResponse() {
        return new ClientHttpResponse() {
            //回退时返回的状态码
            @Override
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }
            //回退时返回的数字状态码
            @Override
            public int getRawStatusCode() throws IOException {
                return this.getStatusCode().value();
            }
            //回退时返回的状态文本
            @Override
            public String getStatusText() throws IOException {
                return this.getStatusCode().getReasonPhrase();
            }

            @Override
            public void close() {

            }
            //回退时响应体
            @Override
            public InputStream getBody() throws IOException {
                return new ByteArrayInputStream("consumer微服务不可用".getBytes());
            }
            //回退时 header
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                MediaType mt = new MediaType("application","json", Charset.forName("UTF-8"));
                httpHeaders.setContentType(mt);
                return httpHeaders;
            }
        };
    }
}
